<?php

namespace app\common\service;

use app\common\model\Order;
use app\common\model\User;
use app\common\model\UserAmount;
use app\common\model\UserAmountRewardDetailed;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Log;

class CommonOrderService
{
    /** 佣金分成方法
     * @param $data
     * @return bool
    */
    public static function commissionSharing($data){
        $time = time();
        if($data["state"]<3||$data["com_state"] == 2||empty($data["commission_info"])){
            return true;
        }
        $now_commission_price = isset($data["commission_info"]["commission_price"])?$data["commission_info"]["commission_price"]:0;
        if($now_commission_price == 0){
            Order::editInfo(["id"=>$data["id"]],["com_state"=>2]);
            return true;
        }
        if($data["sup_uid"]&&isset($data["commission_info"]["sup_commission_price"])&&($data["commission_info"]["sup_commission_price"]>0)){
            $sup_commission_price = $data["commission_info"]["sup_commission_price"];
            $now_commission_price = bcsub($now_commission_price,$sup_commission_price);
            if($sup_commission_price > 0){
                $userPrevAmount =  UserAmount::userAmountInfo(["uid"=>$data["sup_uid"]]);
                $rewardDetailedData = [
                    'uid' => $data["sup_uid"],
                    'amount_money' => $sup_commission_price,
                    'state' => 2,
                    'type' => 1,
                    'balance' => bcadd($userPrevAmount['balance'],$sup_commission_price,2),
                    'freezing_reward_amount' => 0,
                    'to_id' => $data['id'],
                    'remarks' => '下级用户订单['.$data["o_pro_num"].'],赏金到账',
                    'addtime'=> $time,
                    "below_id"=>$data["uid"]
                ];
                UserAmountRewardDetailed::UserAmountRewardDetailedAdd($rewardDetailedData);
                UserAmount::userAmountInc(['uid' => $data["sup_uid"]],"balance",$sup_commission_price);
            }
        }
        if (isset($data["commission_info"]["store_commission_price"])&&($data["commission_info"]["store_commission_price"]>0)){
            if (isset($data["commission_info"]["store_uid"])&&($data["commission_info"]["store_uid"]>0)){
                $store_commission_price = $data["commission_info"]["store_commission_price"];
                $userPrevAmount =  UserAmount::userAmountInfo(["uid"=>$data["commission_info"]["store_uid"]]);
                $now_commission_price = bcsub($now_commission_price,$store_commission_price,2);
                $rewardDetailedData = [
                    'uid' => $data["commission_info"]["store_uid"],
                    'amount_money' => $store_commission_price,
                    'state' => 2,
                    'type' => 1,
                    'balance' => bcadd($userPrevAmount['balance'],$store_commission_price,2),
                    'freezing_reward_amount' => 0,
                    'to_id' => $data['id'],
                    'remarks' => '用户订单['.$data["o_pro_num"].'],佣金到账',
                    'addtime'=> $time,
                    "below_id"=>$data["uid"]
                ];
                UserAmountRewardDetailed::UserAmountRewardDetailedAdd($rewardDetailedData);
                UserAmount::userAmountInc(['uid' => $data["commission_info"]["store_uid"]],"balance",$store_commission_price);
            }
        }
        if($data["ps_id"]&&isset($data["commission_info"]["sta_commission_price"])&&($data["commission_info"]["sta_commission_price"]>0)){
            $sta_commission_price = $data["commission_info"]["sta_commission_price"];
            if($now_commission_price > $sta_commission_price){
                $sta_commission_price = $now_commission_price;
            }
            if($sta_commission_price > 0){
                $userPrevAmount =  UserAmount::userAmountInfo(["uid"=>$data["ps_id"]]);
                $rewardDetailedData = [
                    'uid' => $data["ps_id"],
                    'amount_money' => $sta_commission_price,
                    'state' => 2,
                    'type' => 1,
                    'balance' => bcadd($userPrevAmount['balance'],$sta_commission_price,2),
                    'freezing_reward_amount' => 0,
                    'to_id' => $data['id'],
                    'remarks' => '下级用户订单['.$data["o_pro_num"].'],赏金到账',
                    'addtime'=> $time,
                    "below_id"=>$data["uid"]
                ];
                UserAmountRewardDetailed::UserAmountRewardDetailedAdd($rewardDetailedData);
                UserAmount::userAmountInc(['uid' => $data["ps_id"]],"balance",$sta_commission_price);
            }
        }

        Order::editInfo(["id"=>$data["id"]],["com_state"=>2]);
        return true;
    }

    /** 订单发货信息同步至微信
     * @param $data 订单详情
    */
    public static function orderDeliveryInfoSync($data){
        if(empty($data)){
            return false;
        }
        $item[] =  [
            "tracking_no"=>$data["tracking_no"],
            "item_desc" => $data["p_name"],
            "express_company" => "菜鸟裹裹",
        ];
        // 整理签名数据
        $app_id = Config::get("app.wx_xcx_AppID");
        $key = Config::get("app.wx_xcx_AppSecret");
        $mch_id = Config::get("app.wx_mch_id");
        $token = self::getWxToken($app_id, $key);
        $url = 'https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=' . $token;
        $content = [
            'order_key' => [
                'order_number_type' => 1,
                'mchid' => $mch_id ,
                'out_trade_no' => $data["o_pro_num"]
            ],
            'logistics_type' => 1,
            'delivery_mode' => 1,
            'shipping_list' => $item,
            'upload_time' => (new \DateTime())->format(DATE_RFC3339),
            'payer' => [
                'openid' => $data['openid']
            ]
        ];
        $content = json_encode($content, JSON_UNESCAPED_UNICODE);
        $res = CommonCurlService::post($url,$content);
        $res = object_array(json_decode($res));
        Log::write('快递信息上传结果1：'.json_encode($res, JSON_UNESCAPED_UNICODE));
        Log::write('快递信息上传内容1：'.json_encode($content, JSON_UNESCAPED_UNICODE));
        if($res['errcode']==0&&$res["errmsg"] == 'ok'){
            return true;
//            "{"errcode":0,"errmsg":"ok"}"
        }else{
            return false;
        }
    }




    public static function getWxToken($appid, $secret)
    {
        if(Cache::has("access_token_admin")&&!empty(Cache::get("access_token_admin"))){
            $tokenCache = Cache::get("access_token_admin");
            return $tokenCache;
        }else{
            Cache::delete("access_token_admin");
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
        $token = json_decode(file_get_contents($url, true), true);
        $token = $token['access_token'];
        Cache::set("access_token_admin",$token,3600);
        return $token;
    }
}